package com.ssm.controller;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.socket.TextMessage;

import com.google.gson.GsonBuilder;
import com.ssm.pojo.User;
import com.ssm.websocker.Message;
import com.ssm.websocker.MyWebSocketHandler;

@Controller
@RequestMapping("/msg")
public class MsgController {

	@Autowired
	MyWebSocketHandler handler;

	
	Map<Long, User> users = new HashMap<Long, User>();
	// 模拟一些数据
	@ModelAttribute
	public void setReqAndRes() {
		
		User u1 = new User();
		u1.setChartId(1L);
		u1.setLoginName("张三");
		users.put(u1.getChartId(), u1);
		
		User u2 = new User();
		u2.setChartId(2L);
		u2.setLoginName("李四");
		users.put(u2.getChartId(), u2);
		
		User u3 = new User();
		u3.setChartId(3L);
		u3.setLoginName("李5");
		users.put(u3.getChartId(), u3);

	}

	// 用户登录
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public ModelAndView doLogin(User user, HttpServletRequest request) {
		request.getSession().setAttribute("uid", user.getChartId());
		request.getSession().setAttribute("name", users.get(user.getChartId()).getLoginName());
		return new ModelAndView("redirect:talk");
	}

	// 跳转到交谈聊天页面
	@RequestMapping(value = "/talk", method = RequestMethod.GET)
	public ModelAndView talk() {
		return new ModelAndView("talk");
	}

	// 跳转到发布广播页面
	@RequestMapping(value = "/broadcast", method = RequestMethod.GET)
	public ModelAndView broadcast() {
		return new ModelAndView("broadcast");
	}

	// 发布系统广播（群发）
	@ResponseBody
	@RequestMapping(value = "/broadcast", method = RequestMethod.POST)
	public void broadcast(String text) throws IOException {
		Message msg = new Message();
		msg.setDate(new Date());
		msg.setFrom(-1L);
		msg.setFromName("系统广播");
		msg.setTo(0L);
		msg.setText(text);
		handler.broadcast(new TextMessage(new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create().toJson(msg)));
	}

}